#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include "c-utils/internal/shell.h"

int utils_shell(const char *command, char *result, int length)
{
    FILE *fp = 0;
    int pos = 0;
    int rc = 0;

    fp = popen(command, "r");

    printf("utils_shell,command = %s, fp = %p \n", command, fp);
    if (fp == NULL)
    {
        printf("popen error: %s\n", strerror(errno));
        rc = -1;
        return rc;
    }

    char *line = NULL;
    size_t len = 0;
    ssize_t nread = 0;
    while ((nread = getline(&line, &len, fp)) != -1)
    {
        if (NULL != result && pos < length)
        {
            strncpy(result + pos, line, length - pos);
            pos += nread;
        }
    }
    free(line);

    return pclose(fp);
}
